<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Helper extends CI_Controller {

    function __construct(){
        parent:: __construct();
        if ($this->input->get('debug'))
            $this->output->enable_profiler(true);
        require_once('simple_html_dom.php');
        $this->load->model('common_model', 'common');
        $this->load->model('fetch_model', 'fetch');
        $this->load->model('user_model', 'user');
        $this->load->model('event_model', 'event');
        date_default_timezone_set("Asia/Shanghai");
    }
    public function index(){
        $this->display_event();
    }

    public function get_index($page = 0){
        $this->fetch->get_index($page);
    }

    public function get_all($from, $max) {
        for ($i = $from; $i <= $max; ++$i) {
            $this->fetch->get_index($i * 50);
            echo $i . PHP_EOL;
        }
    }

    public function check_login() {
        $f = fopen('/home/cookies.cookie', 'w');
        fwrite($f, json_encode($_COOKIE));
        fclose($f);
        $this->load->view('input_cookie', array(
                'cookie'    => $_COOKIE,
                'login'     => $this->common->get_tbs()
            ));
    }

    public function add_black_list () {
        print_r($this->event->add_black_list("连云小森森"));
    }

    public function get_all_threads() {
        while ($thread = $this->fetch->get_need_fetch_threads()) {
            echo $thread;
            if (!$this->fetch->get_thread($thread)) {
                $this->db->insert('thread_reply', 
                    array(
                            'tid'   => $thread
                        ));
            }
            echo PHP_EOL;
        }
    }

    public function get_thread(){
        $thread = $this->fetch->get_need_fetch_threads();
        if ($thread === NULL)
            return;
        $this->fetch->get_thread($thread);
    }

    public function get_lzl() {
        $lzl = $this->fetch->get_need_fetch_lzl();

        if ($lzl == NULL)
            return;

        foreach ($lzl AS $id) {
            $this->fetch->get_lzl($id['pid'], $id['tid']);
        }
    }

    public function check_user(){
        $data = $this->get_need_check_user();
        if ($data === NULL)
            return;
        $data = json_decode($data);
        $time = $data->content->date;
        $data = $data->author;
        
        $sql = 'SELECT * FROM user WHERE id=?';
        $result = $this->db->query($sql, array($data->id));
        if ($result->num_rows() == 0){
            $sql = 'INSERT INTO user VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';
            $this->db->query($sql, array(
                $data->id,
                $data->name,
                $data->name_u,
                $data->gender,
                $data->portrait,
                $data->has_grade,
                $data->grade_level,
                $data->grade_name,
                $data->grade_exp,
                $data->fans_num,
                $data->is_concerned,
                $data->is_private,
                $data->outer_id,
                1,
                $time
                ));
        } else {
            if ($result->row()->time < $time){
                $sql = 'UPDATE user SET gender=?, portrait=?, has_grade=?, grade_level=?, grade_name=?, grade_exp=?, fans_num=?, is_concerned=?, is_private=?, need_update=1, date=? WHERE id=?';
                $this->db->query($sql, array(
                    $data->gender,
                    $data->portrait,
                    $data->has_grade,
                    $data->grade_level,
                    $data->grade_name,
                    $data->grade_exp,
                    $data->fans_num,
                    $data->is_concerned,
                    $data->is_private,
                    $time,
                    $data->id
                    ));                
            }
        }
    }

    public function list_bawu($DEBUG = TRUE, $NOCOOKIE = FALSE) {
        if ($NOCOOKIE) {
            $_COOKIE = json_decode(file_get_contents("/home/cookies.cookie"));
            // var_dump($_COOKIE);
        }
        $this->db->query('create table IF NOT EXISTS operation(
                id int primary key auto_increment,
                url varchar(1000),
                title varchar(255),
                user varchar(255),
                operator varchar(255),
                time varchar(255)
                ) default charset utf8;');

        $data = $this->common->fetch_with_cookie('http://tieba.baidu.com/bawu2/platform/listBawuDel?word=%D5%E3%BD%AD%B4%F3%D1%A7', true);

        echo strlen($data);

        $html = new simple_html_dom();
        $html->load($data);
        $tbody = $html->find('table[id=dataTable]', 0);

        $array = array();

        foreach($tbody->find('tr') AS $key => $value) {
            if ($value->find('div.post_content') == NULL)
                continue;

            $item = array();

            $item['url']        = $value->find('div.post_content a', 0)->href;
            $item['title']      = $value->find('div.post_content a', 0)->innertext;
            $item['user']       = $value->find('div.post_author a', 0)->innertext;
            $item['operator']   = $value->find('td', 2)->find('a', 0)->innertext;
            $item['time']       = $value->find('td', 3)->innertext;

            $array[] = $item;
        }
        
        if ($DEBUG) var_dump($array);

        $array = $this->event->save_operation($array);

        var_dump($array);

        foreach($array AS $value) {
            $this->event->post_reply(
                    '用户@' . $value['user'] . ' ，你好！非常抱歉，由于违反吧规，你的帖子 ' . '' . ' 被 ' . $value['operator'] . ' 删除了，如果有任何疑问，请详细阅读一楼并在相应的吧务质询贴中询问，谢谢合作！',
                    $value['url']
                );
        }


    }

    public function process_event(){
        
        $id = $this->get_user_checking();
        if ($id === NULL)
            return;
        $sql = 'SELECT * FROM thread_reply WHERE author_id=? AND has_delete=0 AND in_event=0 ORDER BY date DESC';
        $result = $this->db->query($sql, array($id));
        $result = $result->result();
        $this->check_watering($result, $id);

        $md5helper = array();
        foreach ($result as $key => &$value) {
            $value->md5 = md5(trim($value->content));
            array_push($md5helper, md5(trim($value->content)));
        }
        array_multisort($result, $md5helper);

        $base = null;
        $time = 0;
        foreach ($result as $key => &$value) {
            if ($value->md5 != $base){
                if ($time >= 3){
                    $pid = array();
                    for($i = $key - 1; $i >= $key - $time; --$i)
                        array_push($pid, $result[$i]->pid);
                    $sql = 'SELECT * FROM event WHERE uid=? AND state=? AND type=?';
                    $result = $this->db->query($sql, array($id, 1, 1));
                    if ($result->num_rows() != 0){
                        $sql = 'UPDATE event SET event=? WHERE uid=? AND state=? AND type=?';
                        $this->db->query($sql, array(json_encode($pid), $id, 1, 1));
                    } else {
                        $sql = 'INSERT INTO event(uid, event, state, type) VALUES(?, ?, ?, ?)';
                        $this->db->query($sql, array(
                            $id, 
                            json_encode($pid),
                            $this->state['need_process'],
                            $this->type['watering']
                            ));
                    }
                    
                }
                $base = $value->md5;
                $time = 1;
            } else {
                ++$time;
            }
        }
    }

    public function check_watering(){
        $this->event->check_warting();
    }

    private function check_ads($result, $author_id){
        $pid = array();
        foreach ($result as $key => &$value) {
            if ($this->ads_mb_strstr($value->content))
                array_push($pid, $value->pid);
        }
        if (sizeof($pid) != 0){
            $sql = 'INSERT INTO event(uid, event, state, type) VALUES(?, ?, ?, ?);';
            $this->db->query($sql, array($author_id, json_encode($pid), $this->state['need_process'], $this->type['auto_ads']));
        }
    }

    private function watering_mb_strstr($str){
        $needle = array(
            '标准的十五字',
            '标准十五字',
            '标准的15字',
            '标准15字',
            '十五字经验拿走',
            '十五字够了吧',
            '到底是不是十五字',
            '再凑成十五字',
            '十五字骗经验骗经验骗经验骗经验',
            '鲁迅原名冰心,是著名的反法西斯歌曲家',
            '鲁迅原名冰心，是著名的反法西斯歌曲家',
			'水一水',
			'水一下',
			'水一个',
			'加经验',
			'混脸熟',
			'十五字十五字',
            '夜黑风高，荒郊野岭，小木屋。'
            );
        foreach ($needle as $key => &$value) {
            if (mb_strstr($str, $value))
                return TRUE;
        }
        return FALSE;
    }

    private function ads_mb_strstr($str){
        $needle = array(
            'taobao.com',
            );
        foreach ($needls as $key => &$value) {
            if (mb_strstr($str, $value))
                return TRUE;
        }
        return FALSE;
    }

    public function test_cookie(){
        foreach ($_COOKIE as $key => $value) {
            echo "$key=$value; ";
        }
    }

    public function delete_event(){
        $cookie = $_COOKIE;
        $cookie_str = '';
        foreach ($cookie as $key => $value) {
            $cookie_str .= "$key=$value; ";
        }
        $cookie_str = substr($cookie_str, 0, strlen($cookie_str) - 2);
        $cookie = $cookie_str;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_COOKIE, $cookie);
        curl_setopt($curl, CURLOPT_URL, 'http://tieba.baidu.com/dc/common/tbs');
        curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36");

        $data   = curl_exec($curl);
        $tbs    = json_decode($data);

        $event_id = $this->input->get('event');
        $sql = 'SELECT * FROM event WHERE id=?';
        $result = $this->db->query($sql, array($event_id));
        $pid = $result->row()->event;
        $pid = json_decode($pid);

        $len = 0;
        $cnt_success=0;$cnt_fail=0;
        foreach ($pid as $key => &$value) {
            $sql = 'SELECT * FROM thread_reply WHERE pid=?';
            $result = $this->db->query($sql, array($value))->row();


            $curl = curl_init();
            curl_setopt($curl, CURLOPT_HEADER, 0);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURLOPT_COOKIE, $cookie);
            curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36");

            $post = 'commit_fr=' . urlencode('pb') . 
                '&ie=' . urlencode('utf-8') .
                '&tbs=' . urlencode($tbs->tbs) .
                '&kw=' . urlencode('浙江大学') . 
                '&fid=' . 26074 . 
                '&tid=' . $result->tid . 
                '&is_vipdel=' . 0 . 
                '&pid=' . $result->pid . 
                '&is_finf=' . 'false';
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_URL, 'http://tieba.baidu.com/f/commit/post/delete');
            $data = curl_exec($curl);
            //var_dump($data);
            $data = json_decode($data);
            if ($data->no == 0 || $data->no == 890){    //注意：890代表“贴子不存在”。所以也要清除~啦啦啦啦
                $sql = 'UPDATE thread_reply SET has_delete=1 WHERE pid=?';
                $this->db->query($sql, array($value));
                ++$len;
                $cnt_success++;
            }
            else
            {
                $cnt_fail++;
            }
        }
        echo json_encode((object)array("success"=>$cnt_success,"fail"=>$cnt_fail));

        if ($len != 0){
            $sql = 'UPDATE event SET state=3 WHERE id=?';
            $this->db->query($sql, array($event_id));
        }
        
    }

    public function display_event() {
        $data = $this->event->all_events();

        $this->load->view('header');
        $this->load->view('display_event', array(
                'event' => $data
            ));
    }
}

?>